package com.fruits.controller;
import com.fruits.domain.Fruit;
import com.fruits.service.FruitService;
import com.fruits.service.impl.FruitServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/searchServlet")
public class SearchServlet extends BaseServlet {
    private FruitService fruitService = new FruitServiceImpl();

    //根据关键词搜索
    public String search(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        //1.获取参数
        String keyword = request.getParameter("keyword");
        //2.调用service查询
        if (keyword == null || keyword.trim().length() == 0) {
            keyword = "";
        }
        List<Fruit> fruits = fruitService.findByStr(keyword);

        request.setAttribute("selFruits", fruits);
        //转发

        return "forward:/search.jsp";


    }


    public String all(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
        //1.获取参数
        //2.调用业务层方法
        List<Fruit> all = fruitService.findAll();
        req.setAttribute("selFruits", all);

        return "forward:/search.jsp";

    }

    public String money(HttpServletRequest req, HttpServletResponse resp) {
        String keyword = req.getParameter("keyword");
        int start = 0;
        int end = 0;
        if ("a".equals(keyword)) {
            start = 0;
            end = 100;
        } else if ("b".equals(keyword)) {
            start = 100;
            end = 300;
        } else if ("c".equals(keyword)) {
            start = 300;
            end = 9999;
        }
//2.查询所有水果
        List<Fruit> all = fruitService.findAll();
        List<Fruit> resultList = new ArrayList<>();
        for (Fruit fruit : all) {
            if (fruit.getUp() > start && fruit.getUp() < end){
                req.setAttribute("fruit", fruit);
            resultList.add(fruit);
            }
        }
       req.setAttribute("selFruits", resultList);
        return "forward:/search.jsp";
    }
    public String searchByOrigin(HttpServletRequest req, HttpServletResponse resp){
        List<Fruit> resultList = fruitService.searchByOrigin();
        req.setAttribute("selFruits", resultList);
        return "forward:/search.jsp";

    }
    public String searchByChinaOrigin(HttpServletRequest req, HttpServletResponse resp){
        List<Fruit> resultList = fruitService.searchByChinaOrigin();
        req.setAttribute("selFruits", resultList);
        return "forward:/search.jsp";

    }
}
